package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"strconv"
	"time"
	"weibo-sys/cache"
	"weibo-sys/models"
)

func CommentAdd(c *gin.Context) {
	weibo_id, _ := strconv.Atoi(c.PostForm("weibo_id"))
	content := c.PostForm("content")
	data := models.Comment{
		Model:   gorm.Model{},
		WeiboId: weibo_id,
		Content: content,
	}
	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "评论失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "评论成功",
	})
	return
}
func CommentList(c *gin.Context) {
	var comment []models.Comment
	redis_key := "weibo_list"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Debug().Find(&comment)
		jsonData, _ := json.Marshal(comment)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &comment)
	}
	var total int64
	models.DB.Model(&models.Weibo{}).Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "ok",
		"data":  comment,
		"total": total,
	})
}
